package com.bobi.tfca.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.databinding.ItemMemberRmLayoutBinding
import com.bobi.tfca.network.response.MemberResponse
import com.bobi.tfca.ui.member.MemberRemoveFragment
import com.bumptech.glide.Glide

class GroupMemRmAdapter(
    val fragment: MemberRemoveFragment,
    var memberResponseList: ArrayList<MemberResponse>
) :
    RecyclerView.Adapter<GroupMemRmAdapter.MemberViewHolder>() {

    private var checkedMemberList: ArrayList<Int> = ArrayList()

    fun getCheckedMemberList(): ArrayList<Int> {
        return checkedMemberList
    }

    fun setCheckedMemberList(list: ArrayList<Int>) {
        this.checkedMemberList = list
    }

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }


    inner class MemberViewHolder(private val binding: ItemMemberRmLayoutBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(position: Int) {
            val member = memberResponseList[position]
            binding.member = member
            val url = member.picture
            if (url != null && url.isNotBlank() && (!"null".equals(url))) {
                Glide.with(fragment).load(url).placeholder(R.drawable.default_avatar)
                    .into(binding.memberHead)
            }
            if ("男".equals(member.sex)) {
                Glide.with(binding.ivGender).load(R.mipmap.gender_male).into(binding.ivGender)
            } else {
                Glide.with(binding.ivGender).load(R.mipmap.gender_female).into(binding.ivGender)
            }

            binding.cbMember.isChecked = false

            binding.cbMember.setOnCheckedChangeListener { compoundButton, b ->
                val memberId = member.memberId
                // 如果选中，则添加id
                if (b) {
                    checkedMemberList.add(memberId)
                } else {
                    // 取消选中，移除id
                    checkedMemberList.remove(memberId)
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MemberViewHolder {
        val itemView =
            ItemMemberRmLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        val viewHolder = MemberViewHolder(itemView)
        return viewHolder
    }

    override fun getItemCount(): Int = memberResponseList.size

    override fun onBindViewHolder(holder: MemberViewHolder, position: Int) {
        with(holder) {
            bind(position)
        }
    }
}